package com.cfks.webviewdriver;

import android.annotation.SuppressLint;
import android.content.Context;
import android.os.Build;
import android.text.TextUtils;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import com.cfks.webviewdriver.error.ElementNotFound;
import com.cfks.webviewdriver.error.VersionError;
import java.util.concurrent.atomic.AtomicBoolean;
public class WebviewDriver {
    private WebView webview;
    public WebviewDriver(Context ctx) throws VersionError {
		if (!checkVersion()) {
			throw new VersionError("Build.VERSION.SDK_INT must be greater than 18");
		}
        this.webview = new WebView(ctx);
        this.webview.getSettings().setJavaScriptEnabled(true);
    }
	public WebviewDriver(WebView wv) throws VersionError {
		if (!checkVersion()) {
			throw new VersionError("Build.VERSION.SDK_INT must be greater than 18");
		}
		this.webview = wv;
        this.webview.getSettings().setJavaScriptEnabled(true);
	}
	@SuppressLint("SetJavaScriptEnabled")
    public void get(String url, final OnLoadFinishListener listener) {
        if (TextUtils.isEmpty(url))
            return;
        this.webview.getSettings().setJavaScriptEnabled(true);
        this.webview.setWebChromeClient(new WebChromeClient() {
				private AtomicBoolean mIsLoadFinish = new AtomicBoolean(false);
				@Override
				public void onProgressChanged(WebView view, int newProgress) {
					super.onProgressChanged(view, newProgress);
					if (newProgress == 100) {
						if (!mIsLoadFinish.compareAndSet(false, true)) {
							return;
						}
						if (listener != null) {
							listener.onLoadFinish();
						}
					}
				}
			});
        this.webview.loadUrl(url);
    }

    public interface OnLoadFinishListener {
        void onLoadFinish();
    }
    public Element getElementById(String name) throws ElementNotFound {
        return new Element(name, By.by_id, this, 0);
    }
    public Elements getElementsByClassName(String name) throws ElementNotFound {
        return new Elements(name, By.by_classname, this);
    }
    public void runJS(String js) {
		this.webview.evaluateJavascript("javascript:" + js, null);
    }
    public WebView getWebView() {
        return this.webview;
    }
	private boolean checkVersion() {
		return (Build.VERSION.SDK_INT > 18);
	}
}
